import { computed, watch } from 'vue'
import { MEDIA_TYPE_LABELS } from '@/constant/viewer-router'

export function useCurrentViewer(viewerRouter, index) {
  const { getMediaType, getViewerIndex, getAllFetcher, updateNextCreator } = viewerRouter

  const mediaType = getMediaType(index)
  const viewerIndex = getViewerIndex(index)
  const fetchers = getAllFetcher(index)

  const currIndex = computed({
    get() {
      return viewerIndex[MEDIA_TYPE_LABELS[mediaType.value]]
    },
    set(index) {
      if (index < 0) {
        return
      }
      const label = MEDIA_TYPE_LABELS[mediaType.value]
      if (index > fetchers[label].dataList.length - 1) {
        return
      }
      viewerIndex[label] = index
    },
  })
  const fetcher = computed(() => fetchers[MEDIA_TYPE_LABELS[mediaType.value]])
  const items = computed(() => fetchers[MEDIA_TYPE_LABELS[mediaType.value]].dataList)

  function bindCreatorUpdate(pageActive) {
    function updateCreatorId() {
      if (pageActive.value) {
        updateNextCreator(items.value[currIndex.value]?.author?.aff)
      }
    }
    watch(pageActive, updateCreatorId)
    watch(currIndex, updateCreatorId, { immediate: true })
    watch(mediaType, updateCreatorId)
    watch(items.value, updateCreatorId)
  }

  return {
    mediaType,
    currIndex,
    fetcher,
    bindCreatorUpdate,
  }
}
